import {
  reqGetDoctors,
  reqGetHospitalDepartments,
  reqGetHospitalSchedule,
} from "@/api/hospital/hospitalList/hospitalList";
import {
  Departments,
  HospitalScheduleItem,
  ReqGetDoctorsResponse,
} from "@/api/hospital/hospitalList/model/hospitalTypes";
import { Button, Card, Col, message, Pagination, Row, Space, Tag } from "antd";
import Table, { ColumnsType } from "antd/lib/table";
import Tree, { DataNode } from "antd/lib/tree";
import React, { Key, useEffect, useRef, useState } from "react";
import { useParams } from "react-router-dom";

export default function Schedule() {
  //创建 ref 容器
  let ref = useRef();
  //准备数据
  const treeData: DataNode[] = [
    {
      title: "parent 1",
      key: "0-0",
      children: [
        {
          title: "parent 1-0",
          key: "0-0-0",
          disabled: true,
          children: [
            {
              title: "leaf",
              key: "0-0-0-0",
              disableCheckbox: true,
            },
            {
              title: "leaf",
              key: "0-0-0-1",
            },
          ],
        },
        {
          title: "parent 1-1",
          key: "0-0-1",
          children: [
            {
              title: <span style={{ color: "#1890ff" }}>sss</span>,
              key: "0-0-1-0",
            },
          ],
        },
      ],
    },
  ];

  // 声明表格结构
  let columns: ColumnsType<any> = [
    {
      title: "序号",
      render: (value, row, index) => {
        return index + 1;
      },
    },
    {
      title: "职称",
      dataIndex: "title",
    },
    {
      title: "号源时间",
      dataIndex: "workDate",
    },
    {
      title: "总预约数",
      dataIndex: "reservedNumber",
    },
    {
      title: "剩余预约数",
      dataIndex: "availableNumber",
    },
    {
      title: "挂号费",
      dataIndex: "amount",
    },
    {
      title: "擅长技能",
      dataIndex: "skill",
    },
  ];

  //测试数据
  let arr = [{}, {}];
  //计算左侧 div 的高度
  let height =
    document.documentElement.clientHeight - 64 - 34 - 24 * 2 - 22 - 14;
  //获取 hoscode 的值
  let { hoscode } = useParams();
  //声明科室的状态
  let [departments, setDepartments] = useState<Departments>([]);
  //声明展开科室的 key 状态
  let [exKeys, setExKeys] = useState<string[]>([]);
  //声明与分页相关的状态
  let [current, setCurrent] = useState(1);
  let [total, setTotal] = useState(10);
  let [pageSize, setPageSize] = useState(5);
  //声明排班规则的状态
  let [schedules, setSchedules] = useState<HospitalScheduleItem[]>([]);
  //声明排班医生的状态
  let [doctors, setDoctors] = useState<ReqGetDoctorsResponse>([]);
  //声明状态
  let [hosname, setHosname] = useState("");
  let [depname, setDepname] = useState("");
  let [workDate, setWorkDate] = useState("");
  let [depcode, setDepcode] = useState("");

  //声明一个函数 发送请求
  let getDepartments = async () => {
    //获取所有的科室 [{depname: 'xxx',depcode: 'xxx'}, {depname: 'xxx',depcode: 'xxx'}, ]
    let departments = await reqGetHospitalDepartments(hoscode as string);
    //使用 map 方法为 departments 一级科室添加 disabled 属性
    let newArr = departments.map((item) => {
      item.disabled = true;
      return item;
    });
    //更新状态
    setDepartments(newArr);
    //展开所有的一级科室
    setExKeys(departments.map((item) => item.depcode));
    //获取第一个一级科室中的第一个二级科室
    let depcode = (departments[0].children as Departments)[0].depcode;
    let depname = (departments[0].children as Departments)[0].depname;
    //更新状态
    setDepname(depname);
    setDepcode(depcode);
  };

  //声明函数 获取科室的排班
  let getSchedules = async () => {
    try {
      //发送请求 获取排班规则
      let schedules = await reqGetHospitalSchedule({
        page: current,
        limit: pageSize,
        hoscode: hoscode as string,
        depcode,
      });
      //更新状态
      setSchedules(schedules.bookingScheduleList);
      setTotal(schedules.total);
      //更新医院的名称状态
      setHosname(schedules.baseMap.hosname);

      //获取第一个排班的日期
      let workDate = schedules.bookingScheduleList[0].workDate;
      //更新状态
      setWorkDate(workDate);
    } catch (e) {
      message.error("请求失败");
      //清空医生列表
      setDoctors([]);
    }
  };

  //声明函数 获取排班的医生
  let getDoctors = async () => {
    //发送请求  获取排班医生
    let doctors = await reqGetDoctors({
      hoscode: hoscode as string,
      depcode,
      workDate,
    });
    //更新医生的状态
    setDoctors(doctors);
  };

  //发送请求 获取当前医院的科室
  useEffect(() => {
    //发送请求
    getDepartments();
  }, []);

  //配置 useEffect
  useEffect(() => {
    //判断状态值
    if (!depname) return;
    getSchedules();
  }, [depname, depcode, current, pageSize]);

  //获取排班医生的信息
  useEffect(() => {
    //判断
    if(!workDate) return;
    getDoctors();
  }, [workDate])

  return (
    <Card>
      {/* 路径导航部分 */}
      <p>
        选择：{hosname} / {depname} / {workDate}
      </p>

      {/* 主题内容 */}
      <Row gutter={20}>
        {/* 左侧结构 */}
        <Col span={6}>
          <div
            ref={ref as any}
            style={{
              border: "solid 1px #999",
              height: height,
              overflowY: "scroll",
            }}
          >
            <Tree
              selectedKeys={[depcode]}
              expandedKeys={exKeys}
              treeData={departments as any}
              fieldNames={{
                title: "depname",
                key: "depcode",
              }}
              onSelect={async (selectedKeys: Key[], info: any) => {
                setDepcode(info.node.depcode);
                setDepname(info.node.depname);
              }}
            />
          </div>
        </Col>

        {/* 右侧结构 */}
        <Col span={18}>
          {/* 日期 */}
          <div>
            {schedules.map((item) => {
              return (
                <Tag
                  color={item.workDate === workDate ? "green" : ""}
                  style={{ cursor: "pointer" }}
                  key={item.workDate}
                  onClick={() => {
                    //更新日期状态
                    setWorkDate(item.workDate);
                  }}
                >
                  <div>
                    {item.workDate} {item.dayOfWeek}
                  </div>
                  <div>
                    {item.availableNumber} / {item.reservedNumber}
                  </div>
                </Tag>
              );
            })}
          </div>
          <div className="h-20"></div>
          {/* 分页结构 */}
          <div>
            <Pagination
              current={current}
              total={total}
              pageSize={pageSize}
              onChange={(page: number, pageSize: number) => {
                setCurrent(page);
                setPageSize(pageSize);
              }}
            />
          </div>
          <div className="h-20"></div>

          {/* 表格结构 */}
          <Table
            rowKey={"id"}
            columns={columns}
            dataSource={doctors}
            bordered
            pagination={false}
          />
          <div className="h-20"></div>
          <Button>返回</Button>
        </Col>
      </Row>
    </Card>
  );
}
